<template>
  <div class="main user-layout-register">
    <!--<h3><span>注册</span></h3>-->
    <a-form ref="formRegister" :form="form">
      <a-form-item
        :label="$t('m.system.user.entity.username')"
        :labelCol="{span: 5}"
        :wrapperCol="{span: 19}"
      >
        <a-input size="large" type="text" autocomplete="false" :placeholder="$t('m.system.login.entity.username')"
                 v-decorator="['username', {rules: [{ required: true, message: this.$t('m.system.login.verify.username')}, { validator: this.checkUsername }], validateTrigger: ['change', 'blur'], validateFirst: true}]"></a-input>
      </a-form-item>

      <a-popover placement="rightTop" trigger="click" :visible="state.passwordLevelChecked">
        <template slot="content">
          <div :style="{ width: '240px' }">
            <div :class="['user-register', passwordLevelClass]">{{$t('m.system.login.other.strength')}}：<span>{{ passwordLevelName }}</span></div>
            <a-progress :percent="state.percent" :showInfo="false" :strokeColor=" passwordLevelColor "/>
            <div style="margin-top: 10px;">
              <span>{{$t('m.system.user.verify.password')}}</span>
            </div>
          </div>
        </template>
        <a-form-item
          :label="$t('m.system.login.entity.password')"
          :labelCol="{span: 5}"
          :wrapperCol="{span: 19}"
        >
          <a-input size="large" type="password" @click="handlePasswordInputClick" autocomplete="false"
                   :placeholder="$t('m.system.login.entity.password')"
                   v-decorator="['password', {rules: [{ required: true, message: $t('m.system.user.verify.password')}, { validator: this.handlePasswordLevel }], validateTrigger: ['change', 'blur'], validateFirst: true}]"></a-input>
        </a-form-item>
      </a-popover>
      <a-form-item
        :label="$t('m.system.login.entity.confirmpassword')"
        :labelCol="{span: 5}"
        :wrapperCol="{span: 19}"
      >
        <a-input size="large" type="password" autocomplete="false" :placeholder="$t('m.system.user.entity.confirmpassword')"
                 v-decorator="['password2', {rules: [{ required: true, message: $t('m.system.login.verify.confirmpassword') }, { validator: this.handlePasswordCheck }], validateTrigger: ['change', 'blur'], validateFirst: true}]"></a-input>
      </a-form-item>
      <a-form-item
        :label="$t('m.system.user.entity.email')"
        :labelCol="{span: 5}"
        :wrapperCol="{span: 19}"
      >
        <a-input size="large" type="text" :placeholder="$t('m.system.user.entity.email')"
                 v-decorator="['email', {rules: [{ required: true, type: 'email', message: $t('m.eform.eformConstant.validRule.email_message') }, { validator: this.handleEmailCheck }], validateTrigger: ['change', 'blur'], validateFirst: true}]"></a-input>
      </a-form-item>
      <a-form-item
        :label="$t('m.system.user.entity.phone')"
        :labelCol="{span: 5}"
        :wrapperCol="{span: 19}"
      >
        <a-input size="large" :placeholder="$t('m.system.login.verify.mobile_placeholder')"
                 v-decorator="['mobile', {rules: [{ required: true, pattern: /^1[3456789]\d{9}$/, message: $t('m.system.user.verify.phoneformat') }, { validator: this.handlePhoneCheck } ], validateTrigger: ['change', 'blur'], validateFirst: true}]">
          <a-select slot="addonBefore" size="large" defaultValue="+86">
            <a-select-option value="+86">+86</a-select-option>
            <a-select-option value="+87">+87</a-select-option>
          </a-select>
        </a-input>
      </a-form-item>
      <!--<a-input-group size="large" compact>
            <a-select style="width: 20%" size="large" defaultValue="+86">
              <a-select-option value="+86">+86</a-select-option>
              <a-select-option value="+87">+87</a-select-option>
            </a-select>
            <a-input style="width: 80%" size="large" placeholder="11 位手机号"></a-input>
          </a-input-group>-->
      <a-form-item
        :label="$t('m.system.login.entity.captcha_short')"
        :labelCol="{span: 5}"
        :wrapperCol="{span: 19}"
      >
        <a-row :gutter="16">
          <a-col class="gutter-row" :span="12">
              <a-input size="large" type="text" :placeholder="$t('m.system.login.entity.captcha')"
                       v-decorator="['captcha', {rules: [{ required: true, message: $t('m.system.login.verify.captcha') }], validateTrigger: 'blur', validateFirst: true}]">
                <ych-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
              </a-input>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-button
              size="large"
              :disabled="state.smsSendBtn"
              @click.stop.prevent="getCaptcha"
              v-text="!state.smsSendBtn && $t('m.system.login.other.getCaptcha')||(state.time+' s')"></a-button>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item>
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="register-button"
          :loading="registerBtn"
          @click.stop.prevent="handleSubmit"
          :disabled="registerBtn">{{$t('m.system.login.other.register_short')}}
        </a-button>
        <router-link class="login" :to="{ name: 'login' }">{{$t('m.system.login.other.login_use_existing_account')}}</router-link>
      </a-form-item>

    </a-form>
  </div>
</template>

<script>

  import { mixinDevice } from '@/utils/mixin.js'
  import { postAction } from '@/api/manage'
  import { checkOnlyUser } from '@/api/api'
  import YchConstant from "@/api/YchConstant";

  const levelNames = {
    0: '低',
    1: '低',
    2: '中',
    3: '强'
  }
  const levelClass = {
    0: 'error',
    1: 'error',
    2: 'warning',
    3: 'success'
  }
  const levelColor = {
    0: '#ff0000',
    1: '#ff0000',
    2: '#ff7e05',
    3: '#52c41a',
  }
  export default {
    name: 'Register',
    components: {},
    mixins: [mixinDevice],
    data () {
      return {
        form: this.$form.createForm(this),
        state: {
          time: 60,
          smsSendBtn: false,
          passwordLevel: 0,
          passwordLevelChecked: false,
          percent: 10,
          progressColor: '#FF0000'
        },
        registerBtn: false
      }
    },
    computed: {
      passwordLevelClass () {
        return levelClass[this.state.passwordLevel]
      },
      passwordLevelName () {
        return levelNames[this.state.passwordLevel]
      },
      passwordLevelColor () {
        return levelColor[this.state.passwordLevel]
      }
    },
    methods: {
      checkUsername (rule, value, callback) {
        checkOnlyUser({
          username: value,
        }).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback(this.$t('m.system.login.verify.account_already_exists'))
          }
        })
      },
      handleEmailCheck (rule, value, callback) {
        checkOnlyUser({
          email: value,
        }).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback(this.$t('m.system.login.verify.email_already_exists'))
          }
        })
      },
      handlePasswordLevel (rule, value, callback) {
        let level = 0
        let reg = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/
        if (!reg.test(value)) {
          callback(new Error(this.$t('m.system.user.verify.password')))
        }
        // 判断这个字符串中有没有数字
        if (/[0-9]/.test(value)) {
          level++
        }
        // 判断字符串中有没有字母
        if (/[a-zA-Z]/.test(value)) {
          level++
        }
        // 判断字符串中有没有特殊符号
        if (/[^0-9a-zA-Z_]/.test(value)) {
          level++
        }
        this.state.passwordLevel = level
        this.state.percent = level * 30
        if (level >= 2) {
          if (level >= 3) {
            this.state.percent = 100
          }
          callback()
        } else {
          if (level === 0) {
            this.state.percent = 10
          }
          callback(new Error(this.$t('m.system.user.verify.password_strength')))
        }
      },
      handlePasswordCheck (rule, value, callback) {
        let password = this.form.getFieldValue('password')
        if (value === undefined) {
          callback(new Error(this.$t('m.system.user.verify.password')))
        }
        if (value && password && value.trim() !== password.trim()) {
          callback(new Error(this.$t('m.system.login.verify.password_inconsistency')))
        }
        callback()
      },
      handlePhoneCheck (rule, value, callback) {
        checkOnlyUser({
          phone: value,
        }).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback(this.$t('m.system.user.verify.phoneexist'))
          }
        })
      },
      handlePasswordInputClick () {
        if (!this.isMobile()) {
          this.state.passwordLevelChecked = true
          return
        }
        this.state.passwordLevelChecked = false
      },
      handleSubmit () {
        this.form.validateFields((err, values) => {
          if (!err) {
            postAction(YchConstant.PREFIX_SYSTEM + "/user/register", {
              username: values.username,
              password: values.password,
              email: values.email,
              phone: values.mobile,
              smscode: values.captcha
            }).then((res) => {
              if (!res.success) {
                this.registerFailed(res.message)
              } else {
                this.$router.push({ name: 'registerResult', params: { ...values } }).catch(err => {})
              }
            })
          }
        })
      },
      getCaptcha (e) {
        e.preventDefault()
        let that = this
        this.form.validateFields(['mobile'], { force: true }, (err, values) => {
            if (!err) {
              this.state.smsSendBtn = true
              let interval = window.setInterval(() => {
                if (that.state.time-- <= 0) {
                  that.state.time = 60
                  that.state.smsSendBtn = false
                  window.clearInterval(interval)
                }
              }, 1000)
              const hide = this.$message.loading(this.$t('m.system.user.other.captchaSend')+'..', 0)
              const params = {
                mobile: values.mobile,
                smsmode: '1'
              }
              postAction(YchConstant.PREFIX_SYSTEM + '/sms', params).then((res) => {
                if (!res.success) {
                  this.registerFailed(res.message)
                  setTimeout(hide, 0)
                }
                setTimeout(hide, 500)
              }).catch(err => {
                setTimeout(hide, 1)
                clearInterval(interval)
                that.state.time = 60
                that.state.smsSendBtn = false
                this.requestFailed(err)
              })
            }
          }
        )
      },
      registerFailed (message) {
        this.messageUtil.warning(message, this.$t('m.system.user.verify.register_fail'))
      },
      requestFailed (err) {
        this.messageUtil.warning(((err.response || {}).data || {}).message || this.$t('m.system.user.other.loginError'), '错误')
        this.registerBtn = false
      },
    },
  }
</script>
<style lang="less">
  .user-register {

    &.error {
      color: #ff0000;
    }

    &.warning {
      color: #ff7e05;
    }

    &.success {
      color: #52c41a;
    }

  }

  .user-layout-register {
    .ant-input-group-addon:first-child {
      background-color: #fff;
    }
  }
</style>
<style lang="less" scoped>
  .user-layout-register {

    & > h3 {
      font-size: 16px;
      margin-bottom: 20px;
    }

    .register-button {
      width: 50%;
    }

    .login {
      float: right;
      line-height: 40px;
    }
  }
</style>
